<template>
  <div>
    <a-form-model ref="form" layout="vertical" :model="form" :rules="rules">
      <a-form-model-item label="种子名称" name="name">
        <a-input v-model="form.name" @blur="textTrim('name')" placeholder="可以不填，推送到下载器会自动获取" allowClear/>
      </a-form-model-item>
      <a-form-model-item label="下载链接" name="address">
        <a-textarea v-model="form.address" @blur="textTrim('address')" placeholder="可以推送到下载器进行下载" :rows="5" allow-clear/>
      </a-form-model-item>
      <a-form-model-item label="所属站点" name="siteid">
        <a-select
          v-model="form.siteid"
        >
          <a-select-option v-for="option in siteOptions" :key="option.id" :value="option.id">
            {{ option.name }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="所属分类" name="categoryid">
        <a-select
          v-model="form.categoryid"
        >
          <a-select-option v-for="option in categoryOptions" :key="option.id" :value="option.id">
            {{ option.name }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="描述" name="description">
        <a-textarea v-model="form.description" :rows="3"/>
      </a-form-model-item>
      <template v-if="!form.id">
      <a-divider orientation="left" class="extra-title">下载配置</a-divider>
      <a-form-model-item label="下载器" name="clientid">
        <a-select
          v-model="form.clientid"
        >
          <a-select-option v-for="option in clientOptions" :key="option.id" :value="option.id">
            {{ option.name }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="立即推送" name="startOnAdd">
        <a-switch v-model="form.startOnAdd" />
      </a-form-model-item>
      <a-form-model-item label="是否开始" name="startNow">
        <a-switch v-model="form.startNow" />
      </a-form-model-item>
      <a-form-model-item label="启用目录" >
        <a-checkbox-group v-model="enableFolder">
          <a-checkbox value="siteFolder" name="enableFolder">
            站点目录
          </a-checkbox>
          <a-checkbox value="categoryFolder" name="enableFolder">
            分类目录
          </a-checkbox>
        </a-checkbox-group>
      </a-form-model-item>
      </template>
      <a-divider orientation="left" class="extra-title">自动硬链接</a-divider>
      <a-form-item label="启用" name="autoLink">
        <a-switch v-model="form.autoLink" />
      </a-form-item>
      <a-form-item label="媒体库" name="libraryid">
        <a-select
          v-model="form.libraryid"
        >
          <a-select-option :key="0" :value="0">
            <p class="option-title">仅使用子路径</p>
            <span class="option-desc">请确保子路径在管理目录下</span>
          </a-select-option>
          <a-select-option v-for="option in libraryOptions" :key="option.id" :value="option.id">
            <p class="option-title">{{ option.name }}</p>
            <span class="option-desc">{{ option.folder }}</span>
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="子路径" name="toLink">
        <a-input v-model="form.toLink" @blur="textTrim('toLink')" placeholder="当选择媒体库后，会在其下自动创建目录" allow-clear>
          <a-icon slot="suffix" type="monitor" @click="lintTolink"/>
        </a-input>
      </a-form-item>
    </a-form-model>
    <a-button type="primary" block @click="doSave">
      确定
    </a-button>
  </div>
</template>

<script>
import api from '../../api/api.js'
export default {
  name: 'TorrentAdd',
  props: {
    success: Function,
    failure: Function,
    siteOptions: {
      type: Array,
      default: () => []
    },
    categoryOptions: {
      type: Array,
      default: () => []
    },
    clientOptions: {
      type: Array,
      default: () => []
    },
    libraryOptions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      module: 'torrent',
      loading: false,
      form: {
        name: '',
        address: '',
        siteid: '',
        categoryid: '',
        description: '',
        clientid: '',
        startOnAdd: false,
        startNow: false,
        enableSiteFolder: true,
        enableCategoryFolder: true,
        autoLink: false,
        libraryid: 0,
        toLink: ''
      },
      title0: '',
      enableFolder: ['siteFolder', 'categoryFolder'],
      rules: {
        name: [
          { max: 100, message: '长度需100以内', trigger: 'blur' }
        ],
        // address: [
        //   { required: true, message: '请填写下载链接', trigger: 'blur' },
        //   { max: 1000, message: '长度需为1000以内', trigger: 'blur' }
        // ],
        description: [
          { max: 100, message: '长度需为100以内', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
  },
  methods: {
    setInfo(modelData) {
      this.title0 = modelData.title0
      this.form.name = modelData.title
      this.form.address = modelData.address
      this.form.siteid = this.siteMatch(modelData.address)
      this.form.categoryid = this.categoryMatch(modelData.category)
    },
    siteMatch(val) {
      let matched
      if (val && this.siteOptions.length > 0) {
        const temp = this.splitSite(val)
        matched = this.siteOptions.find(s => {
          const sTemp = this.splitSite(s.address)
          return temp[1] === sTemp[1] && temp[2] === sTemp[2]
        })
      }
      return matched ? matched.id : ''
    },
    splitSite(val) {
      if (val) {
        const temp = val.replace('https://', '').replace('http://')
        return temp.split('/')[0].split('.')
      }
      return []
    },
    categoryMatch(val) {
      let matched
      if (val && this.categoryOptions.length > 0) {
        matched = this.categoryOptions.find(c => val === c.folder)
      }
      return matched ? matched.id : ''
    },
    textTrim(col) {
      this.form[col] = this.form[col] ? this.form[col].trim() : ''
    //   console.log(`'${this.form[col]}'`)
    },
    lintTolink() {
      if (this.form.name) {
        let guess = ''
        const a = this.form.name.split(/\.| |_|\//);
        if (a) guess = a[0]
        let yearMatch = this.form.name.match(/(19|20)\d{2}/g)
        if (!yearMatch && this.title0) {
          yearMatch = this.title0.match(/(19|20)\d{2}/g)
        }
        if (yearMatch) guess += ` (${yearMatch[0]})`

        let seasonMatch = this.form.name.match(/S\d{1,2}/i)
        if (!seasonMatch && this.title0) {
          seasonMatch = this.title0.match(/S\d{1,2}/i)
        }
        if (seasonMatch) guess += `/Season ${parseInt(seasonMatch[0].slice(1))}`

        this.form.toLink = guess
      }
    },
    doSave() {
      this.$refs.form
      .validate()
      .then(async () => {
        this.loading = true
        this.form.enableSiteFolder = this.enableFolder.indexOf('siteFolder') >= 0
        this.form.enableCategoryFolder = this.enableFolder.indexOf('categoryFolder') >= 0
        api.save(this.module, this.form).then(response => {
          if (response.data.code === 1) {
            this.form = {}
            // this.$message.success(response.data.message ? response.data.message : '保存成功')
            // 回调
            this.$nextTick(() => {
                this.success && this.success()
            })
          } else {
            this.$message.error(`保存失败：${response.data.message}`)
            //
            this.failure && this.failure()
          }
        }).catch((error) => {
          this.$message.error(`保存失败：${error.message}`)
        }).then(() => {
          this.loading = false
        })
      })
      .catch(error => {
        console.log('error', error);
      })
    }
  }
}
</script>

<style scoped>
.option-title {
  margin: 0;
}
.option-desc {
  color: gray;
}
</style>
